package com.qf.pay.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import com.qf.pay.config.WXConfig;
import com.qf.pay.service.IpayService;
import com.qf.pck.entity.PackageOrder;
import com.qf.pck.mapper.PackageOrderMapper;
import com.qf.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class PayServiceImpl implements IpayService {


    @Autowired
    private PackageOrderMapper packageOrderMapper;


    @Value("${wx.notify}")
    private String WXNOTIFY;


    @Override
    public R<String> getPayUrl(String orderId) {


        //1：查询订单信息
        PackageOrder order = packageOrderMapper.selectById(orderId);
        if (order == null) {
            return R.fail("","订单不存在");
        }

        //2：调用微信（统一下单接口） 返回code_url
        try {
            String codeUrl = callWxOrderApi(orderId, order.getMoney() * 100);
            return R.ok(codeUrl,"success");
        } catch (Exception exception) {
            exception.printStackTrace();
            return R.fail("","调用微信接口失败");
        }

    }


    private String callWxOrderApi(String orderId,Integer fee) throws Exception{
        //步骤：
        //1:构建配置对象
        WXConfig wxConfig = new WXConfig();

        //2:封装请求参数
        Map requestParamMap = new HashMap();
        requestParamMap.put("appid",wxConfig.getAppID());
        requestParamMap.put("mch_id",wxConfig.getMchID());
        requestParamMap.put("nonce_str", WXPayUtil.generateNonceStr());
        requestParamMap.put("body","购买套餐");

        requestParamMap.put("out_trade_no", orderId);
        requestParamMap.put("total_fee","1");
        requestParamMap.put("notify_url",WXNOTIFY);
        requestParamMap.put("trade_type","NATIVE");


        //3:map转xml
        String requestXML = WXPayUtil.generateSignedXml(requestParamMap, wxConfig.getKey());

        //4:发送请求WXPayRequest request = new WXPayRequest(config);
        WXPayRequest request = new WXPayRequest(wxConfig);
        String responseXML = request.requestWithoutCert("/pay/unifiedorder", UUID.randomUUID().toString(), requestXML, false);
        System.out.println("responseXML = " + responseXML);
        //5:响应结果转map集合
        Map<String, String> map = WXPayUtil.xmlToMap(responseXML);

        //6:获取支付地址
        String code_url = map.get("code_url");
        System.out.println("code_url = " + code_url);

        return  code_url;
    }
}
